package com.huanbao.oil.app.activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.google.gson.Gson;
import com.huanbao.oil.app.R;
import com.huanbao.oil.app.TCP.Data_syn;
import com.huanbao.oil.app.adapter.BaoJing_JiLuAdapter;
import com.huanbao.oil.app.application.MessageEvent;
import com.huanbao.oil.app.commons.DateUtil;
import com.huanbao.oil.app.commons.JsonUtil;
import com.huanbao.oil.app.commons.UtilsLog;
import com.huanbao.oil.app.model.BaoJingResultModel;
import com.huanbao.oil.app.model.BaoJingSearchModel;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

import static com.huanbao.oil.app.activity.MainActivity.MODE_TCP_CLIENT;
import static com.huanbao.oil.app.activity.MainActivity.MODE_TCP_SERVER;

public class BaoJingJiLuFragment extends Fragment {
    public static final String BUNDLE_TITLE = "title";
    @BindView(R.id.baojing_jilu_fragment_listview)
    ListView baojingJiluFragmentListview;
    @BindView(R.id.baojing_jilu_tv_start_time)
    TextView baojingJiluTvStartTime;
    @BindView(R.id.baojing_jilu_tv_end_time)
    TextView baojingJiluTvEndTime;
    @BindView(R.id.baojing_jilu_fragment_btn_end)
    Button baojingJiluFragmentBtnEnd;
    Unbinder unbinder;
    private String mTitle = "DefaultValue";
    private MainActivity mainActivity;

    private BaoJing_JiLuAdapter baoJing_jiLuAdapter;
    String startDate = "", endDate = "";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mainActivity = (MainActivity) getActivity();
        EventBus.getDefault().register(this);
        Bundle arguments = getArguments();
        if (arguments != null) {
            mTitle = arguments.getString(BUNDLE_TITLE);
        }
        View v = inflater.inflate(R.layout.baojingjilu_fragment, null);
        unbinder = ButterKnife.bind(this, v);
        return v;
    }

    @Override
    public void onResume() {
        super.onResume();
        baoJing_jiLuAdapter = new BaoJing_JiLuAdapter(mainActivity, null);
        baojingJiluFragmentListview.setAdapter(baoJing_jiLuAdapter);
        BaoJingSearchModel model = new BaoJingSearchModel();
        model.setCmd_type(9);
        model.setBegin_time("2015-05-16 15:59:34");
        model.setEnd_time("2020-05-16 15:59:39");
        Gson gson = new Gson();
        mainActivity.jsonStr = gson.toJson(model);
        mainActivity.openDoor( mainActivity.jsonStr);
    }

    public static BaoJingJiLuFragment newInstance(String title) {
        Bundle bundle = new Bundle();
        bundle.putString(BUNDLE_TITLE, title);
        BaoJingJiLuFragment fragment = new BaoJingJiLuFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        EventBus.getDefault().unregister(this);
    }

    @OnClick({R.id.baojing_jilu_tv_start_time, R.id.baojing_jilu_tv_end_time, R.id.baojing_jilu_fragment_btn_end})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.baojing_jilu_tv_start_time:
                //时间选择器
                TimePickerView pvTime = new TimePickerBuilder(mainActivity, new OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {//选中事件回调
                        baojingJiluTvStartTime.setText(DateUtil.DateToStrHM3(date));
                        startDate = DateUtil.DateToStrHM3(date);
                        UtilsLog.e("报警记录===startDate==" + startDate);
                    }
                })
                        .setType(new boolean[]{true, true, true, true, true, true})//分别对应年月日时分秒，默认全部显示
                        .setCancelText("取消")//取消按钮文字
                        .setSubmitText("确定")//确认按钮文字
                        .setLabel("年", "月", "日", "时", "分", "秒")
                        .build();
                pvTime.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
                pvTime.show();
                break;
            case R.id.baojing_jilu_tv_end_time:
                //时间选择器
                TimePickerView pvTime2 = new TimePickerBuilder(mainActivity, new OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {//选中事件回调
                        baojingJiluTvEndTime.setText(DateUtil.DateToStrHM3(date));
                        endDate = DateUtil.DateToStrHM3(date);
                        UtilsLog.e("报警记录===startDate==" + endDate);
                    }
                })
                        .setType(new boolean[]{true, true, true, true, true, true})//分别对应年月日时分秒，默认全部显示
                        .setCancelText("取消")//取消按钮文字
                        .setSubmitText("确定")//确认按钮文字
                        .setLabel("年", "月", "日", "时", "分", "秒")
                        .build();
                pvTime2.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
                pvTime2.show();
                break;
            case R.id.baojing_jilu_fragment_btn_end:
                if (!TextUtils.isEmpty(startDate) && !TextUtils.isEmpty(endDate)) {
                    //---------↑↑↑↑↑↑↑↑↑↑报警记录↑↑↑↑↑↑↑↑↑↑--------------
//                    mainActivity.startTCP();
////////                    BaoJingSearchModel model = new BaoJingSearchModel();
////////                    model.setCmd_type(5);
////////                    model.setBegin_time(startDate);
////////                    model.setEnd_time(endDate);
////////                    Gson gson = new Gson();
////////                    mainActivity.jsonStr = gson.toJson(model);
////////                    UtilsLog.e("报警记录===jsonStr==" + mainActivity.jsonStr);
////////                    // Android 4.0 之后不能在主线程中请求HTTP请求
////////                    new Thread(new Runnable() {
////////                        @Override
////////                        public void run() {
////////                            if (mainActivity.client_islink == true) {
////////                                if (!TextUtils.isEmpty(mainActivity.jsonStr)) {
////////                                    sendmessage(mainActivity.jsonStr);
////////                                }
////////                            } else {
////////                                Looper.prepare();
////////                                UtilsLog.e("报警记录===未启动服务先启动服务");
////////                                Toast.makeText(mainActivity, "连接未建立",
////////                                        Toast.LENGTH_SHORT).show();
////////                                Looper.loop();
////////                            }
////////                        }
////////                    }).start();
                    //---------↑↑↑↑↑↑↑↑↑↑报警记录↑↑↑↑↑↑↑↑↑↑--------------
                    BaoJingSearchModel model = new BaoJingSearchModel();
                    model.setCmd_type(9);
                    model.setBegin_time(startDate);
                    model.setEnd_time(endDate);
                    Gson gson = new Gson();
                    mainActivity.jsonStr = gson.toJson(model);
                    mainActivity.openDoor( mainActivity.jsonStr);

                } else {
                    Toast.makeText(mainActivity, "时间不能为空", Toast.LENGTH_LONG).show();
                }
                break;
        }
    }

    //发送数据函数
    public void sendmessage(String message) {
        if (mainActivity.Hex_send == true) {
            byte[] send = Data_syn.hexStr2Bytes(message);
            if (mainActivity.ch_mode == MODE_TCP_SERVER) {
                mainActivity.tcp_service.write(send);
            } else if (mainActivity.ch_mode == MODE_TCP_CLIENT) {
                mainActivity.tcp_client.sendmessage(send);
            }
        } else {
            //非16进制
            byte[] send = message.getBytes();
            if (mainActivity.ch_mode == MODE_TCP_SERVER) {
                mainActivity.tcp_service.write(send);
            } else if (mainActivity.ch_mode == MODE_TCP_CLIENT) {
                mainActivity.tcp_client.sendmessage(send);
            }
        }
    }

    List<BaoJingResultModel> baoJingResultModel = new ArrayList<>();

    @Subscribe(threadMode = ThreadMode.ASYNC, sticky = true)
    public void onMessageEvent(MessageEvent event) {

//        UtilsLog.e("报警记录===接收到的数据=22=" + mainActivity.re_data_show);
        if (mainActivity.TCP_MODE == 4) {
//            UtilsLog.e("报警记录===接收到的数据==" + event.getMessage());
            if (!TextUtils.isEmpty(event.getMessage()) && !"{}".equals(event.getMessage())
                    && !"{[]}".equals(event.getMessage())) {
                try {
                    JSONObject jsonObject = new JSONObject(event.getMessage());
                    int cmd_type = 0;
                    if (jsonObject.has("cmd_type")) {
                        cmd_type = jsonObject.getInt("cmd_type");
                        UtilsLog.e("报警记录===cmd_type==" + cmd_type);
                    }
                    if (cmd_type == 10) {
                        UtilsLog.e("报警记录===进入解析==");
                        if (jsonObject.getString("records") != "[]" && !TextUtils.isEmpty(jsonObject.getString("records"))) {
                            baoJingResultModel = JsonUtil.stringToArray(jsonObject.getString("records"), BaoJingResultModel[].class);
                            if (baoJingResultModel != null && baoJingResultModel.size() > 0) {
                                UtilsLog.e("报警记录===records==");
                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        UtilsLog.e("报警记录===handler==");
                                        Message msg = new Message();
                                        msg.obj = baoJingResultModel;
                                        handler.sendMessage(msg);
                                    }
                                }).start();
                            } else {
                                UtilsLog.e("报警记录===零条数据==");
                            }
                        }
                    } else {
                        UtilsLog.e("报警记录===cmd_type!==6");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    UtilsLog.e("报警记录===进入解析==" + e.getMessage());
                }
            } else {
                UtilsLog.e("报警记录===没有获取到数据==");
            }
        }else {
            UtilsLog.e("报警记录===000000000==");
        }
    }

    private Handler handler = new Handler() {
        //这是默认的方法
        @Override
        public void handleMessage(Message msg) {
            if (msg.obj != null) {
                baoJing_jiLuAdapter = new BaoJing_JiLuAdapter(mainActivity, (List<BaoJingResultModel>) msg.obj);
                baojingJiluFragmentListview.setAdapter(baoJing_jiLuAdapter);
                baojingJiluFragmentListview.setVisibility(View.VISIBLE);
                UtilsLog.e("报警记录===1111111111==");
            } else {
                UtilsLog.e("报警记录===22222222222==");
                baojingJiluFragmentListview.setVisibility(View.GONE);
            }
        }
    };


}
